package com.tencent.sr.iris.activity.service.event.activity;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityCheckResultDTO;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityDTO;
import com.tencent.sr.iris.activity.domain.event.dto.ActivityTaskDTO;
import com.tencent.sr.iris.activity.interfaces.enums.ActivityEventTypeEnum;
import com.tencent.sr.iris.activity.interfaces.event.dto.ActivityEventDTO;
import com.tencent.sr.iris.activity.service.event.task.IrisTaskExecutor;
import com.tencent.sr.iris.activity.service.event.util.ActivityCommonUtilService;
import com.tencent.sr.iris.user.core.service.interfaces.enums.StaffFromTypeEnum;
import com.tencent.sr.iris.user.core.service.interfaces.enums.TutorChannelSettingEnum;
import com.tencent.sr.iris.user.core.service.interfaces.enums.UserLevelEnum;
import com.tencent.sr.iris.user.core.service.interfaces.response.user.IrisQueryUsersInTagsResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * 注：当前活动处理器的对象名称是 活动类型ActivityEventTypeEnum的code
 */
@Slf4j
@Component
public class UserBecomeTraineeActivityExecutor extends AbstractIrisActivityExecutor {


    @Resource
    private ActivityCommonUtilService activityCommonUtilService;

    @Override
    protected void process(ActivityEventDTO msg, ActivityDTO activity, List<String> eventHandingInfoList) {
        //4.活动准入规则校验
        ActivityCheckResultDTO activityFlag = doActivityCheck(activity, msg);
        if (!activityFlag.isSatisfy()) {
            log.info("不满足活动准入规则,activityId={},msg={}", activity, JSONObject.toJSONString(msg));
            eventHandingInfoList.add("不满足活动准入规则,errorMsg=" + activityFlag.getErrorMsg());
            return;
        }

        activity.getActivityTaskDTOS().forEach(t -> {
            //获取任务执行器
            IrisTaskExecutor taskExecutor = getTaskExecutor(msg, activity, t);
            taskExecutor.execute(msg, activity, t, null);
        });

        activityRecordService.addOrUpdateActivityRecord(msg.getUid(), msg.getEventTime(), activity.getBizId(),
                activity.getPeriodType(), activity.getPeriod());
    }

    @Override
    protected void after(ActivityEventDTO eventDTO, ActivityDTO act) {

    }

    @Override
    protected List<ActivityTaskDTO> getTask(ActivityEventDTO eventDTO, ActivityDTO act) {
        return null;
    }


    @Override
    protected void check(ActivityEventDTO eventDTO, ActivityDTO act) {

    }

    @Override
    public ActivityCheckResultDTO doActivityCheck(ActivityDTO activity, ActivityEventDTO msg) {
        String uid = msg.getUid();
        boolean becomeTraineeEvent = Objects.equals(msg.getEventType(), ActivityEventTypeEnum.BECOME_TRAINEE.getCode());

        //校验用户是见习会员
        boolean isTrainee;
        if (becomeTraineeEvent) {
            isTrainee = activityCommonUtilService.waitAndRetry(() -> activityCommonUtilService.isUserLevelInNoCache(uid,
                    Lists.newArrayList(UserLevelEnum.TRAINEE.getValue())), trainee -> !trainee, "收到升级事件，查询用户不是见习会员");
        } else {
            isTrainee = activityCommonUtilService.isUserLevelIn(uid,
                    Lists.newArrayList(UserLevelEnum.TRAINEE.getValue()));
        }
        if (!isTrainee) {
            return ActivityCheckResultDTO.builder().satisfy(false).errorMsg("用户不是见习会员").build();
        }

        //场景值：自营转自购省（ZI_YING），胖鹅析出（PANG_E）,不触发邀请有礼发券
        IrisQueryUsersInTagsResponse userTags;
        if (becomeTraineeEvent) {
            userTags = activityCommonUtilService.waitAndRetry(() -> activityCommonUtilService.queryUserTags(uid),
                    t -> t == null || CollectionUtil.isEmpty(t.getTagIdList()), "查询用户标签信息失败");
        } else {
            userTags = activityCommonUtilService.queryUserTags(uid);
        }

        if (CollectionUtil.containsAny(userTags.getTagIdList(), Arrays.asList(TutorChannelSettingEnum.ZI_YING.getValue(),
                TutorChannelSettingEnum.PANG_E.getValue(), TutorChannelSettingEnum.DUAN_WEI.getValue()))) {
            log.info("上级【{}】的下级【{}】用户升级场景值为自营、胖鹅或断尾", msg.getPid(), uid);
            return ActivityCheckResultDTO.builder().satisfy(false).errorMsg("下级用户升级场景值为自营、胖鹅或断尾，不可参与注册有礼活动").build();
        }

        //校验用户是否 外部未签约
        if (!activityCommonUtilService.isStaffFromTypeIn(uid,
                Lists.newArrayList(StaffFromTypeEnum.OUTER_NON_SIGN, StaffFromTypeEnum.OUTER_SIGN))) {
            log.info("用户不是外部未签约,外部已签约,uid:{},idempotent:{}", uid, msg.getIdempotent());
            return ActivityCheckResultDTO.builder().satisfy(false).errorMsg("用户不是外部未签约,外部已签约").build();
        }

        //判断是否云选新用户
        boolean isYunXuanNewUser = activityCommonUtilService.isYunXuanNewUser(uid);
        if (!isYunXuanNewUser) {
            return ActivityCheckResultDTO.builder().satisfy(false).errorMsg("用户不是云选新用户,无法参与注册有礼活动").build();
        }

        return ActivityCheckResultDTO.builder().satisfy(true).build();
    }

}
